package com.hexanet.server.dao;

import java.lang.reflect.ParameterizedType;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.proxy.HibernateProxy;

import com.hexanet.server.hibernate.HibernateUtil;

public abstract class DataAccessDao<T> {

    private Class<T> entityBeanType;
    private Session session = null;
    
    
    public Session getSession()
    {
	if(session == null || !session.isOpen())
	{
	    session = HibernateUtil.getSession();
	}
	
	return session;
    }

    @SuppressWarnings("unchecked")
    public DataAccessDao() {
	this.entityBeanType = (Class<T>) ((ParameterizedType) getClass()
		.getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public void save(T entity) {

	Transaction transaction = getSession().beginTransaction();
	getSession().save(entity);
	transaction.commit();

    }

    @SuppressWarnings("unchecked")
    public T load(Long id)
    {
	T entity = (T) getSession().get(entityBeanType, id);
	
	return entity;
    }
    
    public void delete(T entity)
    {

	Transaction transaction = getSession().beginTransaction();
	getSession().delete(entity);
	transaction.commit();
    }
    
    @SuppressWarnings("unchecked")
    public T merge(T entity)
    {
	return (T) getSession().merge(entity);
	
    }
    
    
    
}
